package cn.dengta.webapp.trade.entity.meta;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;

import cn.dengta.webapp.trade.entity.meta.MetaConfig.MetaRuleConfig;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
import me.codeplayer.util.*;

/**
 * 甜蜜pick的规则配置对象
 */
@Getter
@Setter
public class SweetPickRule implements MetaRuleConfig {

	/** 奖池 */
	private BigDecimal jackpot;
	/** 投票基数 */
	private Integer factor;
	/** 单次价格 */
	private Integer price;
	/** 星球探险配置 */
	public SweetPickEntry[] entries;

	@Override
	public void validate() {
		final SweetPickEntry[] entries = this.entries;
		Assert.isTrue(X.size(entries) > 0, "甜蜜pick配置不能为空！");
		Assert.isTrue(Cmp.nullToZero(jackpot).compareTo(BigDecimal.ZERO) > 0, "初始奖金池必须大于0！");
		Assert.isTrue(Cmp.nullToZero(price) > 0, "单次价格必须大于0！");
		Assert.isTrue(factor != null && factor > 0 && factor <= 100, "投票基数必须 > 0 且 <= 100！");
		for (int i = entries.length - 1; i > 0; ) {
			SweetPickEntry entry = entries[i--];
			entry.validate();
			SweetPickEntry nextEntry = entries[i];
			nextEntry.validate();
			Assert.isTrue(entry.awardRate <= nextEntry.awardRate, "奖金池比例只能递减！");
		}
		Assert.isTrue(Arrays.stream(entries).map(SweetPickEntry::getAwardRate).reduce(0, Integer::sum) == 100, "奖金池比例总和必须 等于 100!");
	}

	@Override
	public void init(MetaRuleConfig config) {
		SweetPickRule rule = (SweetPickRule) config;
		this.jackpot = rule.jackpot;
		this.factor = rule.factor;
		this.price = rule.price;
		this.entries = rule.entries;
	}

	@JSONField(serialize = false)
	public SweetPickEntry getEntry(Integer level) {
		return entries[level - 1];
	}

	public BigDecimal calcJackpot(Integer vote) {
		return jackpot.add(BigDecimal.valueOf(vote).multiply(BigDecimal.valueOf(factor)).divide(Arith.HUNDRED, 2, RoundingMode.HALF_DOWN));
	}

	/**
	 * 甜蜜pick规则实体
	 */
	@Setter
	@Getter
	public static class SweetPickEntry implements Serializable {

		/** 数量 */
		protected Integer count;
		/** 奖励比例 */
		protected Integer awardRate;

		public SweetPickEntry() {
		}

		public SweetPickEntry(Integer count, Integer awardRate) {
			this.count = count;
			this.awardRate = awardRate;
		}

		public void validate() {
			Assert.isTrue(Cmp.nullToZero(count) > 0, "奖励VIP天数必须大于0！");
			Assert.isTrue(Cmp.nullToZero(awardRate) > 0, "奖金池比例必须大于0！");
		}

	}

}
